package com.example.service.impl;

import com.alibaba.fastjson.JSON;
import com.example.dto.RabbitMqMessageDTO;
import com.example.service.SendService;
import com.example.utils.PubUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import static com.example.constant.MqConstant.EXCHANGE_NAME;
import static com.example.constant.MqConstant.ROUTING_KEY_NAME;

/**
 * 消息发送 业务逻辑层 具体实现
 *
 * @author Lv
 * @date 2023/4/1
 */
@Slf4j
@Service
public class SendServiceImpl implements SendService {
    @Autowired
    private RabbitTemplate rabbitTemplate;

    /**
     * 发送
     */
    @Override
    public void send() {
        String message = "来自发布者的消息";
        String messageJson = JSON.toJSONString(message);
        log.info("消息报文message:{}", messageJson);

        // 封装报文对象
        RabbitMqMessageDTO rabbitMqMessageDTO = RabbitMqMessageDTO.builder()
                .uniqueKey(PubUtils.getUniqueKey())
                /// .uniqueKey("123456abc")
                .jsonData(messageJson)
                .build();

        // 报文对象转换为JSON
        String data = JSON.toJSONString(rabbitMqMessageDTO);
        log.info("消息报文内容:{}", data);

        // 发送消息
        rabbitTemplate.convertAndSend(EXCHANGE_NAME, ROUTING_KEY_NAME, data);
    }
}
